package com.user_hosted_storage.server.utils;

import java.lang.reflect.Constructor;
import java.util.Hashtable;
import java.util.Map;

import org.apache.log4j.Logger;

public class PropertiesParserSingleton {

	private static Logger log = Logger.getLogger(PropertiesParserSingleton.class);
	
	/*
	 * This is a map holding for each PropertiesParser type its unique instance
	 */
	private static Map<Class<? extends PropertiesParser>, PropertiesParser> propertiesParsers = new Hashtable<Class<? extends PropertiesParser>, PropertiesParser>();

	/**
	 * This method returns for a given PropertiesParser inherited class its unique instance.
	 * The method creates the instance if it was not existing
	 * @param <T> PropertiesParser inherited class
	 * @param propClass name of a class inheriting from PropertiesParser
	 * @return the unique instance of propClass
	 * @throws PropertyException If an exception occurs when creating the unique instance of propClass
	 */
	public static <T extends PropertiesParser> T get(Class<T> propClass) throws PropertyException {
		
		// Check if an instance of propClass exists in the map
		//T propertiesParserUniqueInstance = (T) propertiesParsers.get(propClass);
		T propertiesParserUniqueInstance = propClass.cast(propertiesParsers.get(propClass));
		
		if (propertiesParserUniqueInstance == null) {
			// Create an instance of propClass and add it in the map
			try {
				Constructor<T> constructor = propClass.getConstructor();
				constructor.setAccessible(true);
				propertiesParserUniqueInstance = constructor.newInstance();
			} catch (Exception e) {
				log.error("Cannot instanciate properties '" + propClass + "'.", e);
				throw new PropertyException("Cannot instanciate properties '" + propClass + "'. Error is following: " + e.getMessage());
			}
			propertiesParsers.put(propClass, propertiesParserUniqueInstance);
		}
		
		return propertiesParserUniqueInstance;
		
	}
}
